<?php
class ControllerCommunityViewtopic extends Controller{
    private $error=array();

    public function index(){
        $this->language->load('community/viewtopic');
        $this->language->load('community/community_header');
        $this->load->model('community/viewtopic');

        //detect if user login
        $this->load->model('community/user');
        if($this->customer->isLogged()){
            $this->data['is_user_login']=TRUE;
        }else{
            $this->data['is_user_login']=FALSE;
        }

        //posting awarded forum points session
        if(isset($this->session->data['text_forum_points_awarded'])){
            $this->data['text_forum_points_awarded']=$this->session->data['text_forum_points_awarded'];

            unset($this->session->data['text_forum_points_awarded']);
        }else{
            $this->data['text_forum_points_awarded']='';
        }

        $userPermission=$this->model_community_user->getPermission($this->request->get,$this->customer->getForumUserType(),$this->customer->getForumUserRank());

        if($userPermission['role_id']==1 || $userPermission['role_id']==2 || ($userPermission['role_id']==3 && $userPermission['forum_mod_ids'] && in_array($this->customer->getForumUserId(),unserialize($userPermission['forum_mod_ids'])))){
            $is_mod=TRUE;
        }else{
            $is_mod=FALSE;
        }

        //if $_GET['tid'] or $_GET['fid'] does no exists or is empty or is not numeric, redirect
        if(!isset($this->request->get['fid']) || empty($this->request->get['fid']) || !is_numeric($this->request->get['fid']) || !isset($this->request->get['tid']) || empty($this->request->get['tid']) || !is_numeric($this->request->get['tid'])){
            $this->redirect($this->url->link('error/not_found'));
        }

        $result=$this->model_community_viewtopic->getTopicInfo($this->request->get);

        //if no topic are found via $get['tid']
        if(!$result){
            $this->redirect($this->url->link('error/not_found'));
        }

        //if fid of the forum is not the one the current topic is posted in
        if($result['forum_id']!=$this->request->get['fid']){
            $this->redirect($this->url->link('error/not_found'));
        }

        //if user role not allowed to view forum, redirect
        if(!$userPermission['view_forum']){
            $this->session->data['forwarded_link']=$this->url->link('community/community','','SSL');
            $this->session->data['warning_type']='not_allow_view_forum';
            $this->redirect($this->url->link('community/warning'));
        }

        // if forum is disabled
        if(!$result['forum_enabled']){
            $this->session->data['forwarded_link']=$this->url->link('community/community','','SSL');
            $this->session->data['warning_type']='not_allow_view_forum';
            $this->redirect($this->url->link('community/warning'));
        }

        //if topic is allowed to be viewed by the user role, redirect
        if(!$userPermission['topic_view']){
            $this->session->data['forwarded_link']=$this->url->link('community/viewforum','fid=' . $this->request->get['fid'],'SSL');
            $this->session->data['warning_type']='not_allow_view_topic';
            $this->redirect($this->url->link('community/warning'));
        }

        //if topic is not approved
        if($result['topic_approved']==0){
            $this->redirect($this->url->link('error/not_found'));
        }

        //if reply is allowed for the user role
        if(!$result['topic_status'] && $userPermission['topic_reply']){
            $this->data['allow_reply']=TRUE;
        }else{
            $this->data['allow_reply']=FALSE;
        }

        $this->data['topic']=array(
            'topic_title'                 =>  $result['topic_title'],
            'topic_type'                  =>  $result['topic_type'],
            'topic_first_post_id'         =>  $result['topic_first_post_id'],
            'topic_last_post_id'          =>  $result['topic_last_post_id'],
            'topic_polled'                =>  $result['topic_polled'],
            'topic_solved'                =>  $result['topic_solved'],
            'topic_answer_post_id'        =>  $result['topic_answer_post_id'],
            'poll_title'                  =>  $result['poll_title'],
            'poll_max_options'            =>  $result['poll_max_options'],
            'cart_product_id'             =>  $result['cart_product_id'],
            'product_name'                =>  $result['name'],
            'product_link'                =>  $this->url->link('product/product','product_id=' . $result['cart_product_id'],'SSL'),
            'model'                       =>  $result['model'],
            'price'                       =>  $result['price'],
            'points'                      =>  $result['points']
        );

        if($result['topic_your_day']){
            $this->data['is_your_day_topic']=TRUE;

            $your_day_data=$this->model_community_viewtopic->getYourDayNameData($this->request->get['tid']);

            $start_time=$your_day_data['upcoming_date']+(60*60*24)-time();
            $days=floor($start_time/(60*60*24))>0 ? floor($start_time/(60*60*24)) : 0;
            $hours=floor(($start_time-$days*(60*60*24))/(60*60))>0 ? floor(($start_time-$days*(60*60*24))/(60*60)) : 0;
            $mins=floor(($start_time-$days*(60*60*24)-$hours*(60*60))/60)>0 ? floor(($start_time-$days*(60*60*24)-$hours*(60*60))/60) : 0;
            $secs=floor($start_time-$days*(60*60*24)-$hours*(60*60)-$mins*60)>0 ? floor($start_time-$days*(60*60*24)-$hours*(60*60)-$mins*60) : 0;
            $this->data['your_day_name_id']=$your_day_data['name_id'];
            $this->data['your_day_days']=$days;
            $this->data['your_day_hours']=$hours;
            $this->data['your_day_mins']=$mins;
            $this->data['your_day_secs']=$secs;

            if($start_time<0){
                $this->data['is_claim_ended']=TRUE;
            }else{
                $this->data['is_claim_ended']=FALSE;
            }

            $participant_data=$this->model_community_viewtopic->getYourDayParticipants($this->request->get['tid']);
            $this->data['participants']=array();

            foreach($participant_data as $participant){
                $this->data['participants'][]=array(
                    'participant_link'      =>      $this->url->link('community/profile','uid=' . $participant['user_id'],'SSL'),
                    'participant_name'      =>      $participant['username']
                );
            }
        }else{
            $this->data['is_your_day_topic']=FALSE;
        }

        if(isset($result['image'])){
            $temp=explode('.',$result['image']);
            $name_no_ex=rtrim($result['image'],'.' . $temp[count($temp)-1]);

            $this->data['topic']['topic_product_image']=HTTP_IMAGE . 'cache/' . $name_no_ex . '-' . $this->config->get('config_image_thumb_width') . 'x' . $this->config->get('config_image_thumb_height') . '.' . $temp[count($temp)-1];
        }

        if($result['quantity']>0){
            $this->data['topic']['availability']=$this->language->get("text_in_stock");
        }else{
            $this->data['topic']['availability']=$this->language->get("text_out_of_stock");
        }

        if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
            $this->data['topic']['price'] = $this->currency->format($result['price']);
        } else {
            $this->data['topic']['price'] = false;
        }

        if($result['poll_start']+$result['poll_length']>=time()){
            $this->data['show_count_down']=TRUE;

            $this->data['topic']['poll_run_time']=sprintf($this->language->get('text_poll_run_time'),date($this->language->get('date_time_format_short'),$result['poll_start']+$result['poll_length']));

            $start_time=$result['poll_start']+$result['poll_length']-time();

            $this->data['count_down_days']=floor($start_time/(60*60*24))>0 ? floor($start_time/(60*60*24)) : 0;

            $this->data['count_down_hours']=floor(($start_time-$this->data['count_down_days']*(60*60*24))/(60*60))>0 ? floor(($start_time-$this->data['count_down_days']*(60*60*24))/(60*60)) : 0;

            $this->data['count_down_mins']=floor(($start_time-$this->data['count_down_days']*(60*60*24)-$this->data['count_down_hours']*(60*60))/60)>0 ? floor(($start_time-$this->data['count_down_days']*(60*60*24)-$this->data['count_down_hours']*(60*60))/60) : 0;

            $this->data['count_down_secs']=floor($start_time-$this->data['count_down_days']*(60*60*24)-$this->data['count_down_hours']*(60*60)-$this->data['count_down_mins']*60)>0 ? floor($start_time-$this->data['count_down_days']*(60*60*24)-$this->data['count_down_hours']*(60*60)-$this->data['count_down_mins']*60) : 0;

            $this->data['poll_end']=FALSE;
        }elseif(!$result['poll_length']){
            $this->data['poll_end']=FALSE;
            $this->data['show_count_down']=FALSE;
            $this->data['topic']['poll_run_time']=$this->language->get('text_poll_run_time_never_end');
        }else{
            $this->data['poll_end']=TRUE;
            $this->data['show_count_down']=FALSE;
            $this->data['topic']['poll_run_time']=$this->language->get('text_poll_run_time_end');
        }

        //post rating success bar
        if(isset($this->session->data['rating_success'])){
            $this->data['rating_success']=$this->session->data['rating_success'];

            unset($this->session->data['rating_success']);
        }else{
            $this->data['rating_success']='';
        }

        //claim your day freebie success bar
        if(isset($this->session->data['claim_success'])){
            $this->data['claim_success']=$this->session->data['claim_success'];

            unset($this->session->data['claim_success']);
        }else{
            $this->data['claim_success']='';
        }

        //your day freebie failure bar
        if(isset($this->session->data['claim_fail'])){
            $this->data['claim_fail']=$this->session->data['claim_fail'];

            unset($this->session->data['claim_fail']);
        }else{
            $this->data['claim_fail']='';
        }

        //update forum new post notification record
        $this->model_community_viewtopic->updateForumNotification($this->request->get);

        //subscribe topic
        if(isset($this->request->post['subscribe-topic'])){
            $this->model_community_viewtopic->subsribeTopic($this->request->get);

            $this->session->data['forwarded_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
            $this->session->data['success_type']='subscribe_topic';
            $this->redirect($this->url->link('community/success'));
        }

        //bookmark topic
        if(isset($this->request->post['bookmark-topic'])){
            $this->model_community_viewtopic->bookmarkTopic($this->request->get);

            $this->session->data['forwarded_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
            $this->session->data['success_type']='bookmark_topic';
            $this->redirect($this->url->link('community/success'));
        }

        //unsubscribe topic
        if(isset($this->request->post['unsubscribe-topic'])){
            $this->model_community_viewtopic->unsubscribeTopic($this->request->get);

            $this->session->data['forwarded_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
            $this->session->data['success_type']='unsubscribe_topic';
            $this->redirect($this->url->link('community/success'));
        }

        //remove topic bookmark
        if(isset($this->request->post['remove-topic-bookmark'])){
            $this->model_community_viewtopic->TopicBookmarkRemove($this->request->get);

            $this->session->data['forwarded_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
            $this->session->data['success_type']='remove_topic_bookmark';
            $this->redirect($this->url->link('community/success'));
        }

        //detect if subscribed to topic
        $is_subscribed=$this->model_community_viewtopic->DetectSubsribeTopic($this->request->get);

        //detect if topic bookmarked
        $is_bookmarked=$this->model_community_viewtopic->DetectTopicBookmark($this->request->get);

        //delete post
        if(isset($this->request->post['delete-submit'])){
            if($is_mod && $userPermission['post_members_delete']){
                $del_type=$this->model_community_viewtopic->moderatorSoftDeletePost($this->data['topic'],$this->request->post,$this->request->get);
            }elseif($userPermission['post_delete']){
                $del_type=$this->model_community_viewtopic->softDeleteOwnPost($this->data['topic'],$this->request->post,$this->request->get);
            }

            switch($del_type){
                case 'topic_deleted':
                    $this->session->data['forwarded_link']=$this->url->link('community/viewforum','fid=' . $this->request->get['fid'],'SSL');
                    break;
                case 'post_deleted':
                    $this->session->data['forwarded_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
                    break;
            }

            $this->session->data['success_type']='post_del';
            $this->redirect($this->url->link('community/success'));
        }

        //mark topic as solved
        if(isset($this->request->post['solve-submit'])){
            $this->model_community_viewtopic->MarkTopicSolved($this->request->post,$this->request->get);

            $this->session->data['forwarded_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
            $this->session->data['success_type']='solve_topic';
            $this->redirect($this->url->link('community/success'));
        }

        //mark topic as unsolved
        if(isset($this->request->post['unsolve-submit'])){
            $this->model_community_viewtopic->MarkTopicUnsolved($this->request->get);

            $this->session->data['forwarded_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
            $this->session->data['success_type']='unsolve_topic';
            $this->redirect($this->url->link('community/success'));
        }

        //add post thanks
        if(isset($this->request->post['thank-submit'])){
            $this->model_community_viewtopic->addThanks($this->request->post);

            $this->session->data['forwarded_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'] . '&pid=' . $this->request->post['pid'] . '#' . $this->request->post['pid'],'SSL');
            $this->session->data['success_type']='thank_post';
            $this->redirect($this->url->link('community/success'));
        }

        //add post rating
        if(isset($this->request->post['rate-post']) && isset($this->request->post['rating'])){
            $this->model_community_viewtopic->addPostRating($this->request->post, $this->request->get);

            $this->session->data['rating_success']=$this->language->get('text_thank_rating');
            $this->redirect($this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid']));
        }

        // add your day participant
        if(isset($this->request->post['your-day-submit'])){
            if($this->validateYourDayClaimer()){
                $this->model_community_viewtopic->addYourDayParticipant($this->request->post,$this->request->get);

                $this->session->data['claim_success']=$this->language->get('claim_success');
            }

            $this->redirect($this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid']));
        }

        //update topic views only once if visitor keep refreshing the same topic
        if(!isset($this->session->data['last_read_topic_id']) || ($this->session->data['last_read_topic_id']!=$this->request->get['tid'])){
            $this->model_community_viewtopic->updateViewCount($this->request->get);
            $this->session->data['last_read_topic_id']=$this->request->get['tid'];
        }

        //update topic reply record
        $this->model_community_viewtopic->updateTopicNotification($this->request->get);

        //update forum new post notification record
        $this->model_community_viewtopic->updateForumPostNotification($this->request->get);


        $this->document->setTitle($result['topic_title']);

        $this->data['breadcrumbs']=array();

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('common/home'),
            'text'      =>      $this->language->get('text_home'),
            'separator' =>      FALSE
        );

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('community/community'),
            'text'      =>      $this->language->get('text_community'),
            'separator' =>      $this->language->get('text_separator')
        );

        if($result['parent_id']){
            $this->data['breadcrumbs'][]=array(
                'href'      =>      $this->url->link('community/viewforum') . '&fid=' . $result['parent_id'],
                'text'      =>      $result['parent_forum_name'],
                'separator' =>      $this->language->get('text_separator')
            );
        }

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('community/viewforum','fid=' . $result['forum_id'],'SSL'),
            'text'      =>      $result['forum_name'],
            'separator' =>      $this->language->get('text_separator')
        );

        $this->data['text_ucp']=$this->language->get('text_ucp');

        if($this->customer->getForumUserNotifyPm()==0){
            $this->data['text_new_message']=sprintf($this->language->get('text_new_message'),'0');
        }else{
            $this->data['text_new_message']=sprintf($this->language->get('text_new_message'),$this->customer->getForumUserNewPm());
        }

        $this->data['text_by']=$this->language->get('text_by');
        $this->data['text_days']=$this->language->get('text_days');
        $this->data['text_price']=$this->language->get('text_price');
        $this->data['text_reward_points']=$this->language->get('text_reward_points');
        $this->data['text_availability']=$this->language->get('text_availability');
        $this->data['text_sku']=$this->language->get('text_sku');
        $this->data['text_view']=$this->language->get('text_view');
        $this->data['text_note']=$this->language->get('text_note');
        $this->data['text_hours']=$this->language->get('text_hours');
        $this->data['text_mins']=$this->language->get('text_mins');
        $this->data['text_secs']=$this->language->get('text_secs');
        $this->data['text_next_rank']=$this->language->get('text_next_rank');
        $this->data['text_post_num']=$this->language->get('text_post_num');
        $this->data['text_thanks_received']=$this->language->get('text_thanks_received');
        $this->data['text_thanks_givers']=$this->language->get('text_thanks_givers');
        $this->data['text_best_answer_num']=$this->language->get('text_best_answer_num');
        $this->data['text_thanks_received_num']=$this->language->get('text_thanks_received_num');
        $this->data['text_thanks_given_num']=$this->language->get('text_thanks_given_num');
        $this->data['text_view_report']=$this->language->get('text_view_report');
        $this->data['text_join']=$this->language->get('text_join');
        $this->data['text_from']=$this->language->get('text_from');
        $this->data['text_pm']=$this->language->get('text_pm');
        $this->data['text_email']=$this->language->get('text_email');
        $this->data['text_solve_post']=$this->language->get('text_solve_post');
        $this->data['text_unsolve_post']=$this->language->get('text_unsolve_post');
        $this->data['text_thank_post']=$this->language->get('text_thank_post');
        $this->data['text_reply_quote']=$this->language->get('text_reply_quote');
        $this->data['text_report_post']=$this->language->get('text_report_post');
        $this->data['text_delete_post']=$this->language->get('text_delete_post');
        $this->data['text_edit_post']=$this->language->get('text_edit_post');
        $this->data['text_very_poor']=$this->language->get('text_very_poor');
        $this->data['text_poor']=$this->language->get('text_poor');
        $this->data['text_ok']=$this->language->get('text_ok');
        $this->data['text_good']=$this->language->get('text_good');
        $this->data['text_gorgeous']=$this->language->get('text_gorgeous');
        $this->data['text_confirm_solve']=$this->language->get('text_confirm_solve');
        $this->data['text_confirm_unsolve']=$this->language->get('text_confirm_unsolve');
        $this->data['text_confirm_thank']=$this->language->get('text_confirm_thank');
        $this->data['text_confirm_delete']=$this->language->get('text_confirm_delete');
        $this->data['text_view_answer_post']=$this->language->get('text_view_answer_post');
        $this->data['text_participant']=$this->language->get('text_participant');
        $this->data['text_no_participant']=$this->language->get('text_no_participant');
        $this->data['text_login_to_claim']=$this->language->get('text_login_to_claim');
        $this->data['text_claim_end']=$this->language->get('text_claim_end');
        $this->data['text_go']=$this->language->get('text_go');

        $this->data['button_claim']=$this->language->get('button_claim');

        $this->data['entry_jump']=$this->language->get('entry_jump');

        if($is_subscribed){
            $this->data['text_subscribe']=$this->language->get('text_unsubscribe_topic');
            $this->data['text_subsribe_name']=$this->language->get('text_unsubscribe_topic_name');
        }else{
            $this->data['text_subscribe']=$this->language->get('text_subscribe_topic');
            $this->data['text_subsribe_name']=$this->language->get('text_subscribe_topic_name');
        }

        if($is_bookmarked){
            $this->data['text_bookmark']=$this->language->get('text_remove_topic_bookmark');
            $this->data['text_bookmark_name']=$this->language->get('text_remove_topic_bookmark_name');
        }else{
            $this->data['text_bookmark']=$this->language->get('text_bookmark_topic');
            $this->data['text_bookmark_name']=$this->language->get('text_bookmark_topic_name');
        }

        $this->data['headline_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
        $this->data['new_reply_link']=$this->url->link('community/post/reply','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
        $this->data['subscribe_bookmark_action_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
        $this->data['answer_post_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'] . '&pid=' . $this->data['topic']['topic_answer_post_id'] . '#' . $this->data['topic']['topic_answer_post_id'] ,'SSL');

        //poll option and votes
        if($this->data['topic']['topic_polled']){
            //add votes
            if(isset($this->request->post['submit_vote'])){
                if(is_array($this->request->post['poll_option']) && count($this->request->post['poll_option'])>$this->data['topic']['poll_max_options']){
                    echo '<script type="text/javascript">alert("' . sprintf($this->language->get('text_poll_excessive_vote_options'),$this->data['topic']['poll_max_options']) . '")</script>';
                }else{
                    $this->model_community_viewtopic->addVotes($this->request->post,$this->request->get);

                    $this->session->data['topic_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');
                    $this->session->data['success_type']='vote';
                    $this->redirect($this->url->link('community/success'));
                }
            }

            $totalVotes=$this->model_community_viewtopic->getPollVotesTotal($this->request->get);

            $this->data['text_total_votes']=sprintf($this->language->get('text_total_votes'),$totalVotes);
            $this->data['text_poll_max_options']=sprintf($this->language->get('text_poll_max_options'),$this->data['topic']['poll_max_options']);
            $this->data['button_submit_vote']=$this->language->get('button_submit_vote');
            $this->data['poll_action']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'],'SSL');

            if($userPermission['poll_vote']){
                $this->data['user_can_vote']=TRUE;
            }else{
                $this->data['user_can_vote']=FALSE;
            }

            //detect if user has voted
            $results=$this->model_community_viewtopic->getUserVotes($this->request->get);

            $userSelectedOptions=array();

            foreach($results as $result){
                $userSelectedOptions[]=$result['poll_option_id'];
            }

            $userVoteNum=count($results);

            if($userVoteNum>0){
                $this->data['user_has_not_voted']=FALSE;
            }else{
                $this->data['user_has_not_voted']=TRUE;
            }

            //detect if ip has voted within time limit
            if($this->config->get('poll_ip_vote_time_limit')){// if ip vote time limit enabled
                $result=$this->model_community_viewtopic->getIpLastVoteTime($this->request->get);

                if(isset($result['vote_time'])){
                    if(time()>($result['vote_time']+$this->config->get('poll_ip_vote_time_limit'))){
                        $this->data['ip_has_not_voted']=TRUE;
                    }else{
                        $this->data['ip_has_not_voted']=FALSE;
                    }
                }else{
                    $this->data['ip_has_not_voted']=TRUE;
                }
            }else{
                $this->data['ip_has_not_voted']=TRUE;
            }

            $pollOptions=$this->model_community_viewtopic->getPollOptions($this->request->get);

            $this->data['polls']=array();

            $p=0;

            foreach($pollOptions as $pollOption){
                $this->data['polls'][]=array(
                    'poll_option_id'          =>  $pollOption['poll_option_id'],
                    'poll_option_text'        =>  $pollOption['poll_option_text'],
                    'poll_option_total'       =>  $pollOption['poll_option_total'],
                );

                if($totalVotes>0){
                    $this->data['polls'][$p]['poll_option_bar_width']=round($pollOption['poll_option_total']/$totalVotes*400) . 'px';
                    $this->data['polls'][$p]['poll_option_percentage']=round($pollOption['poll_option_total']/$totalVotes*100) . '%';
                }else{
                    $this->data['polls'][$p]['poll_option_bar_width']=0;
                    $this->data['polls'][$p]['poll_option_percentage']=$this->language->get('text_poll_option_no_votes');
                }

                if(isset($this->request->post['submit_vote'])){
                    if(in_array($pollOption['poll_option_id'],$this->request->post['poll_option'])){// only works when poll_max_option >1
                        $this->data['polls'][$p]['is_option_selected']='checked=checked';
                    }else{
                        $this->data['polls'][$p]['is_option_selected']='';
                    }
                }else{
                    $this->data['polls'][$p]['is_option_selected']='';
                }

                $p++;
            }
        }

        //get all post ids and sort them into an array
        $postIdsArr1=$this->model_community_viewtopic->getPostIds($this->request->get);

        $postIdsArr2=array();

        foreach($postIdsArr1 as $postId){
            $postIdsArr2[]=array_shift($postId);
        }

        //pagination
        $url='fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'];
        $pagination = new Pagination();

        $pagination->total=$this->model_community_viewtopic->getPostTotal($this->request->get);

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } elseif(isset($this->request->get['pid']) && !isset($this->request->get['page'])) {
            //directly jump to a post, eg.(community/viewtopic&fid=2&tid=10110&pid=223#223)
            $postPos=array_search($this->request->get['pid'],$postIdsArr2);

            $page=ceil(($postPos+1)/$this->config->get('topic_max_posts_per_page'));
        }else{
            $page = 1;
        }

        //update forum read/unread status track record
        $this->model_community_viewtopic->updateForumTrack($this->request->get,ceil($pagination->total/$this->config->get('topic_max_posts_per_page')));

        //update topics read/unread status track record
        $this->model_community_viewtopic->updateTopicTrack($this->request->get,ceil($pagination->total/$this->config->get('topic_max_posts_per_page')));

        $pagination->page = $page;
        $pagination->limit = (int)$this->config->get('topic_max_posts_per_page');
        $pagination->url = $this->url->link('community/viewtopic', $url . '&page={page}');

        $this->data['pagination'] = $pagination->render();

        $start=($page-1)*$pagination->limit;

        $results=$this->model_community_viewtopic->getPosts($this->request->get,$start,$pagination->limit);

        $this->data['posts']=array();
        $this->data['show_edit_icon']=array();
        $this->data['edit_post_link']=array();
        $this->data['quote_post_link']=array();
        $this->data['odd_even_post']=array();

        $i=0;

        foreach($results as $result){
            $post_contents=$this->parseSpacing($result['post_text']);

            if($result['enable_bbcode']){
                $post_contents=$this->parseBbcode($post_contents,$result);
            }

            if($result['enable_smilies']){
                $post_contents=$this->parseSmiles($post_contents,$result);
            }

            if($result['enable_magic_url']){
                $post_contents=$this->parseURL($post_contents,$result);
            }

            if(unserialize($result['rating'])){
                $rating=array_sum(unserialize($result['rating']))/count(unserialize($result['rating']));

                if($rating>=4.5 && $rating<5){
                    $rating=5;
                }elseif($rating>4 && $rating<4.5){
                    $rating=4;
                }elseif($rating>=3.5 && $rating<4){
                    $rating=4;
                }elseif($rating>3 && $rating<3.5){
                    $rating=3;
                }elseif($rating>=2.5 && $rating<3){
                    $rating=3;
                }elseif($rating>2 && $rating<2.5){
                    $rating=2;
                }elseif($rating>=1.5 && $rating<2){
                    $rating=2;
                }elseif($rating>0 && $rating<1.5){
                    $rating=1;
                }

                $rating_count=count(unserialize($result['rating']));
            }else{
                $rating=FALSE;
                $rating_count=FALSE;
            }

            if($is_mod && $result['post_reported']){
                $this->data['show_reported_post_style'][]=TRUE;
            }else{
                $this->data['show_reported_post_style'][]=FALSE;
            }

            if(!$this->data['topic']['topic_solved'] && ($this->customer->getMasterSlave()!='sl') && (($is_mod && $userPermission['topic_solve'] && $this->data['topic']['topic_first_post_id']!=$result['post_id']) || ($results[0]['poster_id']==$this->customer->getForumUserId() && $this->data['topic']['topic_first_post_id']!=$result['post_id'] && $result['poster_id']!=$this->customer->getForumUserId()))){
                $this->data['show_solve_icon'][]=TRUE;
            }else{
                $this->data['show_solve_icon'][]=FALSE;
            }

            if($this->data['topic']['topic_solved'] && (($is_mod && $userPermission['topic_unsolve'] && $this->data['topic']['topic_first_post_id']==$result['post_id']) || ($results[0]['poster_id']==$this->customer->getForumUserId() && $this->data['topic']['topic_first_post_id']==$result['post_id']))){
                $this->data['show_unsolve_icon'][]=TRUE;
            }else{
                $this->data['show_unsolve_icon'][]=FALSE;
            }

            if(($is_mod && $userPermission['post_members_edit']) || (!$result['post_edit_locked'] && $result['poster_id']==$this->customer->getForumUserId() && $userPermission['post_edit'])){
                $this->data['show_edit_icon'][]=TRUE;
            }else{
                $this->data['show_edit_icon'][]=FALSE;
            }

            if(($is_mod && $userPermission['post_members_delete']) || ($result['poster_id']==$this->customer->getForumUserId() && $result['post_id']==$this->data['topic']['topic_last_post_id'] && $userPermission['post_delete'])){
                $this->data['show_delete_icon'][]=TRUE;
            }else{
                $this->data['show_delete_icon'][]=FALSE;
            }

            if(!$result['post_reported']){
                $this->data['show_report_icon'][]=TRUE;
            }else{
                $this->data['show_report_icon'][]=FALSE;
            }

            if($this->customer->isLogged() && $result['poster_id']!=$this->customer->getForumUserId() && !(!empty($result['thanks_giver_ids']) && in_array($this->customer->getForumUserId(),unserialize($result['thanks_giver_ids'])))){
                $this->data['show_thank_icon'][]=TRUE;
            }else{
                $this->data['show_thank_icon'][]=FALSE;
            }

            if($this->customer->isLogged()){
                if($result['rater_id']){
                    if(in_array($this->customer->getForumUserId(), unserialize($result['rater_id']))){
                        $this->data['show_rating_icon'][]=FALSE;
                    }else{
                        $this->data['show_rating_icon'][]=TRUE;
                    }
                }else{
                    $this->data['show_rating_icon'][]=TRUE;
                }
            }else{
                $this->data['show_rating_icon'][]=FALSE;
            }

            $this->data['post_action_link']=$this->url->link('community/viewtopic','fid=' . $result['forum_id'] . '&tid=' . $result['topic_id'] . '&pid=' . $result['post_id'],'SSL');

            $this->data['pm_action_link'][]=$this->url->link('community/ucp','mode=pm&action=cm&uid=' . $result['user_id'],'SSL');

            $this->data['odd_even_post'][]=($i%2==0) ? 'odd_post' : 'even_post';

            $this->data['edit_post_link'][]=$this->url->link('community/post/edit','fid=' .  $this->request->get['fid'] . '&tid=' . $this->request->get['tid'] . '&pid=' . $result['post_id'],'SSL');

            $this->data['quote_post_link'][]=$this->url->link('community/post/reply','fid=' .  $this->request->get['fid'] . '&tid=' . $this->request->get['tid'] . '&qpid=' . $result['post_id'],'SSL');

            $this->data['report_post_link'][]=$this->url->link('community/report','fid=' .  $this->request->get['fid'] . '&tid=' . $this->request->get['tid'] . '&pid=' . $result['post_id'],'SSL');

            $this->data['posts'][]=array(
                'post_id'                =>  $result['post_id'],
                'poster_id'              =>  $result['poster_id'],
                'post_subject'           =>  $result['post_subject'],
                'post_rating'            =>  $rating,
                'based_on'               =>  sprintf($this->language->get('text_base_on'),$this->url->link('community/viewtopic/review','tid=' . $result['topic_id'] . '&pid=' . $result['post_id']),$rating_count),
                'post_contents'          =>  $post_contents,
                'thanks_received'        =>  $result['thanks_received'],
                'thanks_giver_usernames' =>  unserialize($result['thanks_giver_usernames']),
                'user_thanks_given'      =>  $result['user_thanks_given'],
                'user_thanks_received'   =>  $result['user_thanks_received'],
                'post_username'          =>  $result['post_username'],
                'post_time'              =>  date($this->language->get('date_time_format_long'),$result['post_time']),
                'user_sig'               =>  $this->parseSigSmiles($this->parseSigBbcode($this->parseSpacing($result['user_sig']),$result),$result),
                'user_avatar'            =>  $result['user_avatar'],
                'user_posts'             =>  $result['user_posts'],
                'user_best_answers'      =>  $result['user_best_answers'],
                'user_regdate'           =>  date($this->language->get('date_time_format_short'),$result['user_regdate']),
                'user_allow_pm'          =>  $result['user_allow_pm'],
                'user_allow_email'       =>  $result['user_allow_email'],
                'user_from'              =>  $result['user_from'],
                'user_email'             =>  $result['user_email'],
                'user_role_image'        =>  $result['role_image'],
                'post_edit_reason'       =>  $result['post_edit_reason'],
                'post_edit_count'        =>  $result['post_edit_count'],
                'post_num'               =>  (array_search($result['post_id'],$postIdsArr2) + 1),
                'post_num_link'          =>  $this->url->link('community/viewtopic','fid=' .  $this->request->get['fid'] . '&tid=' . $this->request->get['tid'] . '&pid=' . $result['post_id'] . '#' . $result['post_id'])
            );

            $this->data['posts'][$i]['view_report_link']=$this->url->link('community/mcp','mode=rm&action=or' . '&pid=' . $result['post_id'],'SSL');

            if(isset($result['session_viewonline']) && $result['session_viewonline'] && ($result['session_last_visit_time']+$this->config->get("online_time_span")*60>=time())){
                $this->data['posts'][$i]['is_online']=TRUE;
            }else{
                $this->data['posts'][$i]['is_online']=FALSE;
            }

            $this->data['posts'][$i]['enable_sig']=$result['allow_user_sig'] ? $result['enable_sig'] : FALSE;
            $this->data['posts'][$i]['user_link']=$this->url->link('community/profile','uid=' . $result['poster_id'],'SSL');

            $this->data['posts'][$i]['text_post_edit_remark']=sprintf($this->language->get('text_post_edit_remark'),$this->url->link('community/profile','uid=' . $result['post_edit_user'],'SSL'),$result['editor_user_name'],date($this->language->get('date_time_format_short'),strtotime($result['post_edit_time'])),$result['post_edit_count']);

            $this->data['posts'][$i]['text_post_edit_reason']=sprintf($this->language->get('text_post_edit_reason'),$result['post_edit_reason']);

            if(!empty($result['thanks_giver_ids'])){
                $o=0;
                foreach(unserialize($result['thanks_giver_ids']) as $thanks_giver_id){
                    $this->data['posts'][$i]['thanks_giver_links'][]=$this->url->link('community/profile','uid=' . $thanks_giver_id,'SSL');

                    if($o==9){//only show 10 newest thanks giver user profile link
                        break;
                    }

                    $o++;
                }

                if($result['thanks_received']>10){
                    $this->data['text_thank_other_givers']=sprintf($this->language->get('text_thank_other_givers'),$result['thanks_received']-10);
                }
            }

            if($result['role_id']==5){
                $this->data['posts'][$i]['user_title']=$result['rank_title'];
            }else{
                $this->data['posts'][$i]['user_title']=$result['role_title'];
            }

            if($result['role_id']==5){
                $this->data['posts'][$i]['user_rank_image']=$result['rank_image'];

                //4 stars=1 moon, 4 moons=1 sun, 4 suns=1 crown
                $starNum=$result['rank_stars'];

                $crownNum=floor($starNum/64);
                $starNum=$starNum-64*$crownNum;

                $sunNum=floor($starNum/16);
                $starNum=$starNum-16*$sunNum;

                $moonNum=floor($starNum/4);
                $starNum=$starNum-4*$moonNum;

                $this->data['posts'][$i]['user_rank_stars']=$starNum;
                $this->data['posts'][$i]['user_rank_moons']=$moonNum;
                $this->data['posts'][$i]['user_rank_suns']=$sunNum;
                $this->data['posts'][$i]['user_rank_crowns']=$crownNum;

                $rank=$this->model_community_viewtopic->getNextRank($result['user_rank']);

                if(!$rank){
                    $this->data['percentage']='0%';
                    $this->data['barWidth']=0;
                }else{
                    $this->data['percentage']=round($result['user_posts']/$rank['rank_min']*100,2) . '%';

                    $this->data['barWidth']=round($result['user_posts']/$rank['rank_min'],2) * 150;
                }
            }

            $i++;
        }

        if(isset($this->request->get['page'])){
            $pageStr='&page=' . $this->request->get['page'];
        }else{
            $pageStr='';
        }
        $this->data['title_link']=$this->url->link('community/viewtopic','fid=' . $this->request->get['fid'] . '&tid=' . $this->request->get['tid'] . $pageStr,'SSL');

		if(file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/community/viewtopic.tpl')){
            $this->template=$this->config->get('config_template') . '/template/community/viewtopic.tpl';
		}else{
            $this->template='default/template/community/viewtopic.tpl';
		}	
			
        $this->children = array(
            'common/column_left',
			'common/column_right',
			'common/content_top',
			'common/content_bottom',
			'common/footer',
			'common/header',
			'community/community_header',
		);
		
		$this->response->setOutput($this->render()); 	
  	}

    public function review(){
        $this->load->language('community/viewtopic');
        $this->load->model('community/viewtopic');

        $this->data['text_rater_name']=$this->language->get('text_rater_name');
        $this->data['text_rating_level']=$this->language->get('text_rating_level');
        $this->data['text_rating_time']=$this->language->get('text_rating_time');

        $this->data['raters']=$this->model_community_viewtopic->getPostRating($this->request->get['tid'],$this->request->get['pid']);

        if(file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/community/postreview.tpl')){
            $this->template=$this->config->get('config_template') . '/template/community/postreview.tpl';
        }else{
            $this->template='default/template/community/postreview.tpl';
        }

        $this->response->setOutput($this->render());
    }

    private function parseSpacing($str){
        $str=nl2br($str);
        $str = str_replace("\t", '&nbsp; &nbsp;', $str);
        $str = str_replace('  ', '&nbsp; ', $str);
        $str = str_replace('  ', ' &nbsp;', $str);

        return $str;
    }

    private function parseBbcode($str,$posterPermission){
    if($this->config->get('bbcode_parsing_enable')){
        if($posterPermission['posting_bbcode']){
            $pattern=array();
            $pattern[]='/\[size=(\d+)\](.*)\[\/size\]/Uis';
            $pattern[]='/\[b\](.*)\[\/b\]/Uis';
            $pattern[]='/\[i\](.*)\[\/i\]/Uis';
            $pattern[]='/\[u\](.*)\[\/u\]/Uis';
            $pattern[]='/\[color=(#[0-9a-f]{3}|#[0-9a-f]{6}|[a-z\-]+)\](.*)\[\/color\]/Uis';

            if($this->config->get('bbcode_url_parsing_enable')){
                if($posterPermission['posting_bbcode_url']){
                    $pattern[]='/\[url\](.*)\[\/url\]/Uis';
                    $pattern[]='/\[url=([^\[]+?)\](.*)\[\/url\]/Uis';
                }
            }

            $pattern[]='/\[quote(?!&quot;.*&quot;)\](.*)\[\/quote\]/Uis';
            $pattern[]='/\[quote=&quot;(.*)&quot;\](.*)\[\/quote\]/Uis';
            $pattern[]='/\[code\](.*)\[\/code\]/Uis';

            if($this->config->get('bbcode_img_parsing_enable')){
                if($posterPermission['posting_bbcode_img']){
                    $pattern[]='/\[img\](.*)\[\/img\]/Uis';
                }
            }

            if($this->config->get('bbcode_flash_parsing_enable')){
                if($posterPermission['posting_bbcode_flash']){
                    $pattern[]='/\[flash\](.*)\[\/flash\]/Uis';
                }
            }

            $pattern[]='/\[youtube\](http:\/\/)?(www\.)?youtube.com\/watch\?v=(.*)(&amp;\w*=.*)?\[\/youtube\]/Uis';
            $pattern[]='/\[story\](.*)\[\/story\]/Uis';

            $replace=array();
            $replace[]='<span style="font-size:\1%;">\2</span>';
            $replace[]='<strong>\1</strong>';
            $replace[]='<em>\1</em>';
            $replace[]='<span style="text-decoration:underline;">\1</span>';
            $replace[]='<span style="color:\1;">\2</span>';

            if($this->config->get('bbcode_url_parsing_enable')){
                if($posterPermission['posting_bbcode_url']){
                    $replace[]='<a href="\1" target="_blank">\1</a>';
                    $replace[]='<a href="\1" target="_blank">\2</a>';
                }
            }

            $replace[]='<blockquote class="bbcode_uncited"><div>\1</div></blockquote>';
            $replace[]='<blockquote class="bbcode_uncited"><div><dl><dt>\1 Wrote:</dt><dd>\2</dd></dl></div></blockquote>';
            $replace[]='<dl class="bbcode_code"><dt>CODE: <a href="javascript:void(0)" onclick="selectCode(this); return FALSE;">SELECT ALL</a></dt><dd><code>\1</code></dd></dl>';

            if($this->config->get('bbcode_img_parsing_enable')){
                if($posterPermission['posting_bbcode_img']){
                    $replace[]='<img src="\1" />';
                }
            }

            if($this->config->get('bbcode_flash_parsing_enable')){
                if($posterPermission['posting_bbcode_flash']){
                    $replace[]='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" height="400" width="480"><param name="quality" value="high" /><param name="movie" value="\1" /><embed height="400" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="\1" type="application/x-shockwave-flash" width="480"></embed></object>';
                }
            }

            $replace[]='<iframe width="560" height="315" src="http://www.youtube.com/embed/\3" frameborder="0" allowfullscreen></iframe>';
            $replace[]= '<blockquote class="bbcode_story"><div><dl><dt>' . $this->language->get('text_story_mode') . '</dt><dd>\1</dd></dl></div></blockquote>';

            $str=preg_replace($pattern,$replace,$str);
        }
    }

    return $str;
}

    private function parseSmiles($str,$posterPermission){
        if($this->config->get('smiles_parsing_enable')){
            if($posterPermission['posting_smiles']){
                $smileCode=array(
                    ':D',
                    ':)',
                    ';)',
                    ':(',
                    ':o',
                    ':shock:',
                    ':?',
                    '8-)',
                    ':lol:',
                    ':x',
                    ':P',
                    ':-oops:',
                    ':cry:',
                    ':evil:',
                    ':twisted:',
                    ':roll:',
                    ':!:',
                    ':-?:',
                    ':idea:',
                    ':arrow:',
                    ':|',
                    ':mrgreen:',
                    ':geek:',
                    ':ugeek:',
                );

                $smileImage=array(
                    '<img src="catalog/view/theme/default/image/smilies/01_very_happy.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/02_smile.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/03_wink.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/04_sad.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/05_surprised.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/06_shocked.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/07_confused.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/08_cool.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/09_langhing.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/10_mad.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/11_razz.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/12_embarrassed.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/13_cry.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/14_evil_or_very_mad.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/15_twisted_evil.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/16_rolling_eyes.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/17_exclamation.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/18_question.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/19_idea.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/20_arrow.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/21_neutral.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/22_mr._green.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/23_geek.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/24_uber_geek.gif" />'
                );

                $str=str_replace($smileCode,$smileImage,$str);
            }
        }

        return $str;
    }

    private function parseSigBbcode($str,$posterPermission){
        if($this->config->get('bbcode_parsing_enable')){
            if($posterPermission['allow_user_sig_bbcode']){
                $pattern=array();
                $pattern[]='/\[size=(\d+)\](.*)\[\/size\]/Uis';
                $pattern[]='/\[b\](.*)\[\/b\]/Uis';
                $pattern[]='/\[i\](.*)\[\/i\]/Uis';
                $pattern[]='/\[u\](.*)\[\/u\]/Uis';
                $pattern[]='/\[color=(#[0-9a-f]{3}|#[0-9a-f]{6}|[a-z\-]+)\](.*)\[\/color\]/Uis';

                if($this->config->get('bbcode_url_parsing_enable')){
                    if($posterPermission['allow_user_sig_bbcode_url']){
                        $pattern[]='/\[url\](.*)\[\/url\]/Uis';
                        $pattern[]='/\[url=([^\[]+?)\](.*)\[\/url\]/Uis';
                    }
                }

                $pattern[]='/\[quote(?!&quot;.*&quot;)\](.*)\[\/quote\]/Uis';
                $pattern[]='/\[quote=&quot;(.*)&quot;\](.*)\[\/quote\]/Uis';
                $pattern[]='/\[code\](.*)\[\/code\]/Uis';

                if($this->config->get('bbcode_img_parsing_enable')){
                    if($posterPermission['allow_user_sig_bbcode_img']){
                        $pattern[]='/\[img\](.*)\[\/img\]/Uis';
                    }
                }

                if($this->config->get('bbcode_flash_parsing_enable')){
                    if($posterPermission['allow_user_sig_bbcode_flash']){
                        $pattern[]='/\[flash\](.*)\[\/flash\]/Uis';
                    }
                }

                $pattern[]='/\[youtube\](http:\/\/)?(www\.)?youtube.com\/watch\?v=(.*)(&amp;\w*=.*)?\[\/youtube\]/Uis';

                $replace=array();
                $replace[]='<span style="font-size:\1%;">\2</span>';
                $replace[]='<strong>\1</strong>';
                $replace[]='<em>\1</em>';
                $replace[]='<span style="text-decoration:underline;">\1</span>';
                $replace[]='<span style="color:\1;">\2</span>';

                if($this->config->get('bbcode_url_parsing_enable')){
                    if($posterPermission['allow_user_sig_bbcode_url']){
                        $replace[]='<a href="\1" target="_blank">\1</a>';
                        $replace[]='<a href="\1" target="_blank">\2</a>';
                    }
                }

                $replace[]='<blockquote class="bbcode_uncited"><div>\1</div></blockquote>';
                $replace[]='<blockquote class="bbcode_uncited"><div><dl><dt>\1 Wrote:</dt><dd>\2</dd></dl></div></blockquote>';
                $replace[]='<dl class="bbcode_code"><dt>CODE: <a href="javascript:void(0)" onclick="selectCode(this); return FALSE;">SELECT ALL</a></dt><dd><code>\1</code></dd></dl>';

                if($this->config->get('bbcode_img_parsing_enable')){
                    if($posterPermission['allow_user_sig_bbcode_img']){
                        $replace[]='<img src="\1" />';
                    }
                }

                if($this->config->get('bbcode_flash_parsing_enable')){
                    if($posterPermission['allow_user_sig_bbcode_flash']){
                        $replace[]='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" height="400" width="480"><param name="quality" value="high" /><param name="movie" value="\1" /><embed height="400" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="\1" type="application/x-shockwave-flash" width="480"></embed></object>';
                    }
                }

                $replace[]='<iframe width="560" height="315" src="http://www.youtube.com/embed/\3" frameborder="0" allowfullscreen></iframe>';

                $str=preg_replace($pattern,$replace,$str);
            }
        }

        return $str;
    }

    private function parseSigSmiles($str,$posterPermission){
        if($this->config->get('smiles_parsing_enable')){
            if($posterPermission['allow_user_sig_smiles']){
                $smileCode=array(
                    ':D',
                    ':)',
                    ';)',
                    ':(',
                    ':o',
                    ':shock:',
                    ':?',
                    '8-)',
                    ':lol:',
                    ':x',
                    ':P',
                    ':-oops:',
                    ':cry:',
                    ':evil:',
                    ':twisted:',
                    ':roll:',
                    ':!:',
                    ':-?:',
                    ':idea:',
                    ':arrow:',
                    ':|',
                    ':mrgreen:',
                    ':geek:',
                    ':ugeek:',
                );

                $smileImage=array(
                    '<img src="catalog/view/theme/default/image/smilies/01_very_happy.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/02_smile.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/03_wink.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/04_sad.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/05_surprised.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/06_shocked.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/07_confused.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/08_cool.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/09_langhing.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/10_mad.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/11_razz.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/12_embarrassed.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/13_cry.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/14_evil_or_very_mad.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/15_twisted_evil.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/16_rolling_eyes.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/17_exclamation.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/18_question.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/19_idea.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/20_arrow.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/21_neutral.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/22_mr._green.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/23_geek.gif" />',
                    '<img src="catalog/view/theme/default/image/smilies/24_uber_geek.gif" />'
                );

                $str=str_replace($smileCode,$smileImage,$str);
            }
        }

        return $str;
    }

    private function parseURL($str,$posterPermission){
        if($this->config->get('auto_url_parsing_enable')){
            if($posterPermission['posting_bbcode_url']){
                $pattern=$replace=array();
                // matches an "xxxx://yyyy" URL at the start of a line, or after a space.xxxx can only be alpha characters. yyyy is anything up to the first space, newline, comma, double quote or <
                $pattern[]='/(^|[\n ])([\w]+?:\/\/[^ \"\n\r\t<]*)/is';
                // matches a "www|ftp.xxxx.yyyy[/zzzz]" kinda lazy URL thing.Must contain at least 2 dots. xxxx contains either alphanum, or "-". zzzz is optional.. will contain everything up to the first space, newline,comma, double quote or <.
                $pattern[]='/(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)/is';
                // matches an email@domain type address at the start of a line, or after a space. Note: Only the followed chars are valid; alphanums, "-", "_" and or ".".
                $pattern[]='/(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)/i';

                $replace[]='\\1<a href="\\2" target="_blank">\\2</a>';
                $replace[]='\\1<a href="http://\\2" target="_blank">\\2</a>';
                $replace[]='\\1<a href="mailto:\\2@\\3">\\2@\\3</a>';

                $str=preg_replace($pattern,$replace,$str);
            }
        }

        return $str;
    }

    private function validateYourDayClaimer(){
        $result=$this->model_community_viewtopic->validateYourDayClaimer($this->request->post);

        if($result==='wrong_name'){
            $this->session->data['claim_fail']=$this->error['claiming']=$this->language->get('error_wrong_name');
        }

        if($result==='claimed'){
            $this->session->data['claim_fail']=$this->error['claiming']=$this->language->get('error_claimed');
        }

        if($this->customer->getMasterSlave=='sl'){
            $this->session->data['claim_fail']=$this->error['claiming']=$this->language->get('error_claimed');
        }

        if(!$this->error){
            return TRUE;
        }else{
            return FALSE;
        }
    }
}
?>